<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Modules\Core\Services\Visual\VisualService;

class PassportClient extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'authclient';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修改passport客户端，一个个人访问认证客户端，一个管理员访问认证客户端，一个用户访问认证客户端';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // $personal_client = \Laravel\Passport\Client::find(1);
        // 更新第二个客户端 为管理员认证客户端
        \Laravel\Passport\Client::query()->where('id', 2)->update([
            'name' => 'admin',
            'provider' => 'admins',
        ]);
        $admin_client = \Laravel\Passport\Client::find(2);
        // 创建一个个人访问认证客户端
        $user_client = \Laravel\Passport\Client::query()->create([
            'name' => 'teacher',
            'secret' => Str::random(40),
            'provider' => 'teachers',
            'redirect' => 'http://localhost',
            'personal_access_client' => true,
            'password_client' => true,
            'revoked' => false,
        ]);

        // 修改 env 文件
        // OAUTH_ADMIN_CLIENT_ID=2
        // OAUTH_ADMIN_CLIENT_SECRET=
        // OAUTH_USER_CLIENT_ID=3
        // OAUTH_USER_CLIENT_SECRET=
        # 获取个人令牌需要设置这个 【oauth_clients 表中对应id列字段 personal_access_client 设置为：1】
        // PASSPORT_PERSONAL_ACCESS_CLIENT_ID=3
        // PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=
        $ac = "OAUTH_ADMIN_CLIENT_ID=" . env("OAUTH_ADMIN_CLIENT_ID", "");
        $acs = "OAUTH_ADMIN_CLIENT_SECRET=" . env("OAUTH_ADMIN_CLIENT_SECRET", "");
        $uc = "OAUTH_TEACHER_CLIENT_ID=" . env("OAUTH_TEACHER_CLIENT_ID", "");
        $ucs = "OAUTH_TEACHER_CLIENT_SECRET=" . env("OAUTH_TEACHER_CLIENT_SECRET", "");
        $pc = "PASSPORT_PERSONAL_ACCESS_CLIENT_ID=" . env("PASSPORT_PERSONAL_ACCESS_CLIENT_ID", "");
        $pcs = "PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=" . env("PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET", "");
        shell_exec('sed -i "s/' . $ac . '/OAUTH_ADMIN_CLIENT_ID=' . $admin_client->id . '/" .env');
        shell_exec('sed -i "s/' . $acs . '/OAUTH_ADMIN_CLIENT_SECRET=' . $admin_client->secret . '/" .env');
        shell_exec('sed -i "s/' . $uc . '/OAUTH_TEACHER_CLIENT_ID=' . $user_client->id . '/" .env');
        shell_exec('sed -i "s/' . $ucs . '/OAUTH_TEACHER_CLIENT_SECRET=' . $user_client->secret . '/" .env');
        shell_exec('sed -i "s/' . $pc . '/PASSPORT_PERSONAL_ACCESS_CLIENT_ID=' . $user_client->id . '/" .env');
        shell_exec('sed -i "s/' . $pcs . '/PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET=' . $user_client->secret . '/" .env');

        return;
    }
}
